package pt.agap2.relationchat;

import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

import pt.agap2.relationchat.utils.AuthenticationObject;
import pt.agap2.relationchat.utils.MockServerCommunication;
import pt.agap2.relationchat.utils.Constants;

public class MainActivity extends Activity implements View.OnClickListener{


    private Button btnLogin;
    private EditText txtUser;
    private EditText txtPassword;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);

        btnLogin = (Button) findViewById(R.id.mainBtnLogin);
        btnLogin.setOnClickListener(this);
        txtUser = (EditText) findViewById(R.id.mainTxtUser);
        txtPassword = (EditText) findViewById(R.id.mainTxtPassword);

        SharedPreferences settings = getSharedPreferences(Constants.PREFS_NAME, 0);
        SharedPreferences.Editor editor = settings.edit();
        editor.putString(Constants.KEY_APP_TOKEN, Constants.APP_TOKEN);
        editor.commit();
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}


    @Override
    public void onClick(View v){
        switch (v.getId()){
            case R.id.mainBtnLogin:
                String username = txtUser.getText().toString();
                String password = txtPassword.getText().toString();
                MockServerCommunication msc = new MockServerCommunication();
                SharedPreferences settings = getSharedPreferences(Constants.PREFS_NAME, 0);
                String appToken = settings.getString(Constants.KEY_APP_TOKEN, Constants.APP_TOKEN);
                AuthenticationObject ao = msc.logIn(appToken, username, password);

                Log.d("ARC", String.format("user status {0}", ao.status));
                Log.d("ARC", String.format("user token {0}", ao.userToken));
                if(ao.status.equals("Authorized")){
                    SharedPreferences.Editor editor = settings.edit();
                    editor.putString(Constants.KEY_STATUS, ao.status);
                    editor.putString(Constants.KEY_USER_TOKEN, ao.userToken);
                    editor.commit();

                    Intent intent = new Intent(getApplicationContext(), UserlistActivity.class);
                    startActivity(intent);
                }
            break;

        }

    }
}
